package com.ilovepostcard;


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKEvent;
import com.ilovepostcard.controller.OffLineManager;
import com.ilovepostcard.controller.PostcardController;
import com.ilovepostcard.controller.UserController;
import com.ilovepostcard.data.CurrentLocation;
import com.ilovepostcard.data.OffLinePostcard;
import com.ilovepostcard.data.Postcard;
import com.ilovepostcard.utils.Constants;
import com.ilovepostcard.utils.ImageUtil;
import com.ilovepostcard.utils.NetWorkUtil;
import com.ilovepostcard.utils.RotateBitmap;
import com.ilovepostcard.utils.Utils;
import com.ilovepostcard.view.EditPostcardView;
import com.ilovepostcard.view.PostcardMainMenu;
import com.mobclick.android.MobclickAgent;
import com.smedio.imageprocess.ImageProcess;

public class EditImageActivity extends BaseActivity implements OnClickListener{
	
	private static final String NET_BAIDU_LOC_URL = "http://api.map.baidu.com/geocoder?output=json&location=";
	public static final int EFFECT_ORG = 0;
	public static final int EFFECT_CROP = 1;
	public static final int EFFECT_BLACK_WHITE = 2;
	public static final int EFFECT_OIL_PAINT = 3;
	public static final int EFFECT_LOMO = 4;
	public static final int EFFECT_POLAROID = 5;
	public static final int EFFECT_BRIGHTNESS = 6;
	public static final int EFFECT_SKETCH = 7;
	public static final int EFFECT_ART = 8;
	public static final int EFFECT_AMELIORATE = 9;
	public static final int EFFECT_DIM = 10;
	public static final int EFFECT_OLDIMAGE = 11;
	public static final int EFFECT_ROTAT = 12;
	private final static int DLG_ID_PROCESSING = 3;
	
	GridView options;
	EditPostcardView mEditImage;
	Button confirm;
	Button rotat;
	ImageView mReturn;
	Bitmap currentBitmap;
	Bitmap orgBitmap;
	int effectFlag;
	Button retake;
	int selectedPosition;
	AsyncImageProcessTask mAsyncImageProcessTask;
	ArrayList<Integer> selectedQueue = new ArrayList<Integer>();
	BMapManager mBMapMan;
	Uri cameraUri;
	boolean isLocationInitialized;
	boolean isLocationThreadRunning;
	@Override
    public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		
		Intent intent = getIntent();
		Bundle bundle =  intent.getExtras();
		DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);        
        
        int nowWidth = dm.widthPixels; //当前分辨率 宽度
        int nowHeigth = dm.heightPixels; //当前分辨率高度
        
        Log.e("ps", ",nowWidth:"+nowWidth+",nowHeigth:"+nowHeigth);
		String from = bundle.getString("type");
		Bitmap bm = null;
		Uri uri= null;
		if(from.equals("gallery") || from.equals("camera"))
		{
			uri = bundle.getParcelable("uri");
			bm = readBitmapByUri(this,uri,1);
		}
		else if(from.equals("offline"))
		{
			String offline = bundle.getString("name");
			OffLinePostcard offlinePc = OffLineManager.getInstance().getOffLineByName(offline);
			bm = readBitmapByFile(this,offlinePc.getImagePath(),1);
		}
		setContentView(R.layout.activity_editimage);
		init();
		
		
		if(from.equals("offline"))
		{
			String offline = bundle.getString("name");
			initOffLineImageData(offline);
			int page = OffLineManager.getInstance().getResumePage(this);
			if(page>1)
			{
				Intent nextPage = new Intent(EditImageActivity.this,EditTextActivity.class);
				EditImageActivity.this.startActivity(nextPage);
			}
			else
			{
				OffLineManager.getInstance().clearResumeInfo(this);
			}
		}
		else
		{
			initImageData(bm);
		}
		
		MobclickAgent.onEvent(this, Constants.COUNT_CREAT_EDIT);
		
	}
	protected void onNewIntent (Intent intent) 
	{
		super.onNewIntent(intent);
		Bundle bundle =  intent.getExtras();
		
		String from = bundle.getString("type");
		Bitmap bm = null;
		Uri uri= null;
		if(from.equals("gallery") ||  from.equals("camera"))
		{
			uri = bundle.getParcelable("uri");
			bm = readBitmapByUri(this,uri,1);
		}
		else if(from.equals("offline"))
		{
			String offline = bundle.getString("name");
			OffLinePostcard offlinePc = OffLineManager.getInstance().getOffLineByName(offline);
			bm = readBitmapByFile(this,offlinePc.getImagePath(),1);
		}
		init();
		
		
		if(from.equals("offline"))
		{
			String offline = bundle.getString("name");
			initOffLineImageData(offline);
			int page = OffLineManager.getInstance().getResumePage(this);
			if(page>1)
			{
				Intent nextPage = new Intent(EditImageActivity.this,EditTextActivity.class);
				EditImageActivity.this.startActivity(nextPage);
			}
			else
			{
				OffLineManager.getInstance().clearResumeInfo(this);
			}
		}
		else
		{
			initImageData(bm);
		}
	}
	private Bitmap preProcessBitmap(Bitmap b)
	{
		Bitmap newB = null;
		
		int w =  b.getWidth();
		if(w > EditPostcardView.EXPECTWIDTH)
		{
			float Factor = (float)EditPostcardView.EXPECTWIDTH/(float)w;
			newB = Bitmap.createScaledBitmap(b, EditPostcardView.EXPECTWIDTH, (int)(Factor*b.getHeight()), true);
			b.recycle();
			b = null;
		}
		else
			newB = b;
		return newB;
	}
	private void initImageData(Bitmap bitmap)
	{
		
		if(bitmap == null)
		{
			Toast.makeText(this, R.string.error_selectImage, Toast.LENGTH_SHORT).show();
			finish();
			return;
		}
		//Bitmap tmp = preProcessBitmap(bitmap);
		Postcard newPc = new Postcard();
		newPc.user = UserController.getLoginUser(this);
		//newPc.image = bitmap;
		newPc.setTmpEditPC(bitmap);
		java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy.MM.dd"); 
		newPc.createTime =format.format(new java.util.Date());
		currentBitmap = bitmap;
		orgBitmap = currentBitmap;
		PostcardController.getInstance().createNewPostcard(newPc);
		OffLinePostcard pc = OffLineManager.getInstance().getCurrentBackupPC();
		pc.save(OffLinePostcard.TAG_USERID, UserController.getLoginUser(this).UserID+"");
		pc.save(OffLinePostcard.TAG_DATE, newPc.createTime);
		pc.saveImage(currentBitmap);
		mEditImage.setOrignalBitmap(bitmap);
		if(OffLineManager.getInstance().getCurrentBackupPC()!= null)
			OffLineManager.getInstance().updateOffLinePc(this, OffLineManager.getInstance().getCurrentBackupPC().getName(), 1);

	}
	
	private void initOffLineImageData(String name)
	{
		OffLinePostcard offline = OffLineManager.getInstance().getOffLineByName(name);
		if(offline == null)
		{
			Toast.makeText(this, R.string.error_selectImage, Toast.LENGTH_SHORT).show();
			finish();
			return;
		}
		
		Bitmap bitmap = readBitmapByFile(this,offline.getImagePath(),1);
		
		if(bitmap == null)
		{
			Toast.makeText(this, R.string.error_selectImage, Toast.LENGTH_SHORT).show();
			OffLineManager.getInstance().clearResumeInfo(this);
			finish();
			return;

		}
		Postcard newPc = new Postcard();
		newPc.user = UserController.getLoginUser(this);
		newPc.setTmpEditPC(bitmap);
		//newPc.image = bitmap;
		java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy.MM.dd"); 
		newPc.createTime =format.format(new java.util.Date());;
		newPc.comment = offline.get(OffLinePostcard.TAG_COMMENT);
		newPc.location = offline.get(OffLinePostcard.TAG_LOCATION);
		currentBitmap = bitmap;
		orgBitmap = currentBitmap;
		PostcardController.getInstance().createNewPostcard(newPc);
		OffLinePostcard pc = OffLineManager.getInstance().getCurrentBackupPC();
		pc.save(OffLinePostcard.TAG_DATE, newPc.createTime);
		mEditImage.setOrignalBitmap(bitmap);
	}
	
	
	private void init()
	{
		
		currentLocation.setLocation("Shanghai");
		currentLocation.setmCurrLat("31.2243531");
		currentLocation.setmCurrLng("121.4759159");
		
		mBMapMan = new BMapManager(this);
		mBMapMan.init(this.mStrKey, new MyGeneralListener());
		mBMapMan.getLocationManager().setNoitifyInternal(10, 5);
		

		effectFlag = EFFECT_ORG;
		options = (GridView)this.findViewById(R.id.edit_effect_option);
		options.setAdapter(new ImageAdapter());
		options.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				
				ImageAdapter adapter  = (ImageAdapter)options.getAdapter();
				adapter.setSelectPosition(arg2);
				
				int flag = EFFECT_ORG;
				switch(arg2)
				{
				case 0:
					Bitmap org = orgBitmap.copy(Config.ARGB_8888, true);
					if(currentBitmap!= null && !currentBitmap.isRecycled())
						currentBitmap.recycle();
					commitWorkingBitmap(org);
					flag = EFFECT_ORG;
					effectFlag = flag;
					return;
				case 7:
					flag = EFFECT_DIM;
					break;
					
				case 4:
					flag = EFFECT_AMELIORATE;
					break;
				case 1:
					flag = EFFECT_BRIGHTNESS;
					break;
				case 2:
					flag = EFFECT_ART;
					break;
				case 3:
					flag = EFFECT_BLACK_WHITE;
					break;
				case 5:
					flag = EFFECT_LOMO;
					break;
				case 6:
					flag = EFFECT_OLDIMAGE;
					break;
				case 8:
					flag = EFFECT_OIL_PAINT;
					break;
				case 9:
					flag = EFFECT_SKETCH;
					break;

				}
				
				if(effectFlag == flag && flag != EFFECT_ROTAT) return;
				
				proccessImage(flag,currentBitmap);
			}
			
		});
		
		mEditImage = (EditPostcardView)findViewById(R.id.edit_eidtor);
		mEditImage.reset();
		

		confirm = (Button)findViewById(R.id.edit_confirm);
		confirm.setOnClickListener(this);
		
		mReturn = (ImageView)findViewById(R.id.title_return);
		mReturn.setOnClickListener(this);
		
		rotat = (Button)findViewById(R.id.edit_rotat);
		rotat.setOnClickListener(this);
		
		retake = (Button)findViewById(R.id.edit_retake);
		retake.setOnClickListener(this);
	}
	
	public void onBackPressed()
	{
		
		if(PostcardController.getInstance().getCurrentPostCard() != null)
		{
			
			Utils.showConfirmDialog(this, getString(R.string.confirmExit_createPC), new Runnable() {
	            public void run() {
	            	
	            	OffLineManager.getInstance().clearResumeInfo(EditImageActivity.this);
	            	Intent intent = new Intent(EditImageActivity.this,MainActivity.class);
	        		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	        		startActivity(intent);
	            }
	        }, new Runnable() {
	            public void run() {
	            }
	        });
		}
		else
			super.onBackPressed();
		
		releaseImageData();
	}
	
	protected void onResume()
	{
		super.onResume();
		enableLocationSettings();
		MobclickAgent.onResume(this); 
	}
	
	protected void onPause()
	{
		super.onPause();
		MobclickAgent.onPause(this);
		mBMapMan.getLocationManager().removeUpdates(mLocationListener);
		mBMapMan.stop();
		isLocationInitialized = false;
	}
	
	
	protected void onDestroy()
	{
		super.onDestroy();
	}
	
	private void releaseImageData()
	{
		if(orgBitmap!= null &&  !orgBitmap.isRecycled())
			orgBitmap.recycle();
		orgBitmap = null;
		
		if(currentBitmap!= null &&  !currentBitmap.isRecycled())
			currentBitmap.recycle();
		currentBitmap = null;
		
		mEditImage.release();
	}
	
	protected Dialog onCreateDialog( int id )
    {
        if( id == DLG_ID_PROCESSING )
        {
            ProgressDialog processDlg = new ProgressDialog( this );
            processDlg.setMessage(getResources().getString(R.string.loading));
            processDlg.setIndeterminate( true );
            processDlg.setCancelable( false );
			return processDlg;
        }       

        return super.onCreateDialog( id );
	}	
	
	 @Override
	    protected void onActivityResult(int requestCode, int resultCode, Intent data)
	    {
	    	
	    	if (resultCode != RESULT_OK) 
	    	{
	    		Toast.makeText(this, R.string.error_selectImage, Toast.LENGTH_SHORT).show();
	    		return;
	    	}
				
	    	
	    	Bitmap bm = null;
	    	Uri uri = null;
	    	try {
	    		
	    		if (requestCode == ImageUtil.GALLERY) {
	    			uri = data.getData();
	    			bm = readBitmapByUri(this,uri,1);
	    			
	    		} 
		    	else if (requestCode == ImageUtil.CAMERA)
		    	{
		    		uri = cameraUri;
	    			bm = readBitmapByUri(this,uri,1);
		    	}
	    	} 
			catch (Exception e) {
				Toast.makeText(this, R.string.error_selectImage, Toast.LENGTH_SHORT).show();
			}
	    	
	    	if(bm!= null)
	    	{
	    		releaseImageData();
	    		init();
	    		initImageData(bm);
	    	}

	    	
	    }

	
	private synchronized Bitmap proccessImage(int flag, Bitmap src)
	{
		
		Bitmap tmp = null;
		if(effectFlag != flag && flag != EFFECT_ROTAT)
			tmp = orgBitmap.copy(Config.ARGB_8888, true);
		else
			tmp = currentBitmap.copy(Config.ARGB_8888, true);
		
		mAsyncImageProcessTask = new AsyncImageProcessTask();
    	mAsyncImageProcessTask.setActivity(this);
    	mAsyncImageProcessTask.execute(tmp, flag);
    	effectFlag = flag;
		return src;
		
	}
	
	private Bitmap readBitmapByUri(Context c,Uri selectedImage,int sampleSize)
	{
		Bitmap bitmap =null;
		try
		{
			bitmap = readBitmap(c,selectedImage,sampleSize);
		}
		catch(OutOfMemoryError e)
		{
			
			bitmap = readBitmapByUri(this,selectedImage,sampleSize *= 2);
		}
		finally
		{
			
		}
		return bitmap; 
		
	}
	
	public static Bitmap readBitmapByFile(Context c,String path,int sampleSize)
	{
		Bitmap bitmap =null;
		try
		{
			bitmap = BitmapFactory.decodeFile(path);
		}
		catch(OutOfMemoryError e)
		{
			
			bitmap = readBitmapByFile(c,path,sampleSize *= 2);
		}
		finally
		{
			
		}
		return bitmap; 
		
	}
	
	private Bitmap readBitmap(Context c,Uri selectedImage,int sampleSize) { 
		Bitmap bm = null; 
		BitmapFactory.Options options = new BitmapFactory.Options(); 
		//options.inSampleSize = sampleSize; 
		
		options.inJustDecodeBounds = true;
		AssetFileDescriptor fileDescriptor =null; 
		try { 
		fileDescriptor = this.getContentResolver().openAssetFileDescriptor(selectedImage,"r"); 
		} catch (FileNotFoundException e) { 
		e.printStackTrace(); 
		} 
		finally{ 
		try { 
			BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options); 
			
			int w = options.outWidth > options.outHeight ? options.outWidth : options.outHeight;
			int h = options.outWidth < options.outHeight ? options.outWidth : options.outHeight;
			int factor =1;
			int bew = w / (EditPostcardView.EXPECTWIDTH/10);
		     if(bew%10 !=0)
		    	 bew+=10;
		     bew=bew/10;
		     if (bew <= 0)
		    	 bew = 1;
		     
		     int beh = h / (EditPostcardView.EXPECTHEIGHT/10);
		     if(beh%10 !=0)
		    	 beh+=10;
		     beh=beh/10;
		     if (beh <= 0)
		    	 beh = 1;
		     
		     factor = bew < beh ? bew :beh;
		     options.inSampleSize = factor;
			 //options.inJustDecodeBounds = false;
			 BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options); 
			 
			 int outW = options.outWidth > options.outHeight ? options.outWidth :options.outHeight;
			 int outH = options.outWidth < options.outHeight ? options.outWidth :options.outHeight;
			 if(factor >1 && (outW < EditPostcardView.EXPECTWIDTH || outH < EditPostcardView.EXPECTHEIGHT))
			 {
				 options.inSampleSize = factor-1;
				
			 }
			 
			 BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options); 
			 
			 int outW2 = options.outWidth > options.outHeight ? options.outWidth :options.outHeight;
			 int outH2 = options.outWidth < options.outHeight ? options.outWidth :options.outHeight;
			 if(factor >1 && (outW2 < EditPostcardView.EXPECTWIDTH || outH2 < EditPostcardView.EXPECTHEIGHT))
			 {
				 options.inSampleSize = factor-1;
				
			 }
			 
			 //Toast.makeText(this, "Selected Image w:"+options.outWidth+",h:"+options.outHeight, Toast.LENGTH_LONG).show();
			 
			 BitmapFactory.Options optionsFinal = new BitmapFactory.Options(); 
			 optionsFinal.inJustDecodeBounds = false;
			 optionsFinal.inSampleSize = options.inSampleSize;
			 bm = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, optionsFinal); 
			fileDescriptor.close(); 
		} catch (Exception e) { 
			e.printStackTrace(); 
		} 
		} 
		
		return bm; 
		} 
	
	 
	private class AsyncImageProcessTask extends AsyncTask<Object, Object, Object>
	{
		private EditImageActivity mEditImageActivity;
		
		public AsyncImageProcessTask()
		{
		}
		
		public void setActivity(EditImageActivity EditImageActivity)
		{
			mEditImageActivity = EditImageActivity;
		}
		
		@Override
		protected void onPreExecute()
		{
			if (mEditImageActivity != null)
			{
				mEditImageActivity.showDialog(DLG_ID_PROCESSING);
			}
		}
		
		private Bitmap effectPolaroid(Bitmap src)
		{
			try {
				int w = src.getWidth();
				int h = src.getHeight();
				int border = 20;
				Bitmap polaroid = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
				Canvas canvas = new Canvas(polaroid);
				Paint vPaint = new Paint();
				
				// draw border
				vPaint.setColor(0xFFFFFFFF);
				vPaint.setShadowLayer(10, 3, 3, 0xFFa1a1a1);
				vPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
				// draw rect and shader
				canvas.drawRect(0, 0, w, h, vPaint);				
				vPaint.setShadowLayer(0, 0, 0, 0);
				float scale = Math.min((float) (w-2*border)/w, (float) (h-2*border)/h);
				Matrix m = new Matrix();
	            m.setScale(scale, scale);
//				Bitmap scaledBitmap = createBitmap(src, 0, 0, w, h, m);
				Bitmap scaledBitmap = Bitmap.createBitmap(src, 0, 0, w, h, m, true);
				src.recycle();
				int dx = (w-scaledBitmap.getWidth())/2;
				int dy = (h-scaledBitmap.getHeight())/2;
				Rect rect =new Rect(dx, dy, w - dx, h - dy);
				canvas.drawBitmap(scaledBitmap, null, rect, vPaint);
				scaledBitmap.recycle();
				canvas = null;
				ImageProcess.effectPolaroid(polaroid);
				return polaroid;
			}  catch (OutOfMemoryError oom) {				
				Log.d("postcard", Log.getStackTraceString(oom));
			} catch (Throwable t) {
			}
			return null;
		}


		@Override
		protected Object doInBackground(Object... args)
		{
			Bitmap b = (Bitmap)args[0];
			int effectID = (Integer)args[1];
			
			
			switch(effectID)
			{
			case ImageProcess.EFFECT_BLACK_WHITE:
				ImageProcess.effectBlackWhite(b);
				break;
			case ImageProcess.EFFECT_OIL_PAINT:
				ImageProcess.effectOilPaint(b, 4, 40);	
				break;
			case ImageProcess.EFFECT_OLDIMAGE:
				b = ImageProcess.oldRemeber(b);
				break;
			case ImageProcess.EFFECT_LOMO:
				ImageProcess.effectLomo(b);
				break;
			case ImageProcess.EFFECT_POLAROID:
				b = effectPolaroid(b);
				break;
			case ImageProcess.EFFECT_BRIGHTNESS:
				int level =60;// (Integer)args[2];
				ImageProcess.effectBrightness(b, level);
				break;
			case ImageProcess.EFFECT_SKETCH:
				ImageProcess.effectSketch(b);
				break;
			case ImageProcess.EFFECT_ART:
				ImageProcess.effectLomo(b);
				b = ImageProcess.effectArt(EditImageActivity.this,b,Utils.randomIntroduction(EditImageActivity.this));
				break;
			case EFFECT_ROTAT:
				RotateBitmap rB = new RotateBitmap(b,90);
				
				Bitmap res = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), rB.getRotateMatrix(), false);
				b.recycle();
				b = res;
				break;
			case EFFECT_AMELIORATE:
				try
				{
					b = ImageProcess.sharpenImageAmeliorate(b);
				}
				catch(OutOfMemoryError OOM)
				{
					Toast.makeText(EditImageActivity.this, "内存不足!", Toast.LENGTH_SHORT).show();
				}
				
				break;
			case EFFECT_DIM:
				try
				{
					b = ImageProcess.blurImageAmeliorate(b);
				}
				catch(OutOfMemoryError OOM)
				{
					Toast.makeText(EditImageActivity.this, "内存不足!", Toast.LENGTH_SHORT).show();
				}
				
				
				break;
			}
			return b;
		}
		
		@Override
		protected void onPostExecute(Object result)
		{
			Bitmap b = (Bitmap)result;
			if (mEditImageActivity != null)
			{
				if (b != null && !b.isRecycled())
				{
					mEditImageActivity.commitWorkingBitmap(b);
					b = null;
				}
				mEditImageActivity.dismissDialog(DLG_ID_PROCESSING);
				mEditImageActivity = null;
			}
			
			if(effectFlag == EFFECT_ART)
				Toast.makeText(EditImageActivity.this, R.string.wenqing_tip, Toast.LENGTH_SHORT).show();
		}
	}
	
	private synchronized void commitWorkingBitmap(Bitmap work)
	{
		try {
			
			if(currentBitmap!= null && !currentBitmap.isRecycled() && !currentBitmap.equals(orgBitmap)&& !currentBitmap.equals(work))
				currentBitmap.recycle();
			
			currentBitmap =work.copy(Bitmap.Config.ARGB_8888, true);
			mEditImage.setDrawBitmap(currentBitmap);
			
			if(work!= null && !work.isRecycled())
				work.recycle();
			
		} catch (OutOfMemoryError oom) {
			oom.printStackTrace();
		} catch (Throwable t) {
			t.printStackTrace();

		}
	}
	
	
	
	class ImageAdapter extends BaseAdapter
	{
		
		int selectedIndex;
		int[] res =new int[] {
					R.drawable.cpage_edit_effect_original,
					R.drawable.cpage_edit_effect_addeffect,
					R.drawable.cpage_edit_effect_art,
					R.drawable.cpage_edit_effect_black,
					R.drawable.cpage_edit_effect_class,
					R.drawable.cpage_edit_effect_lomo,
					R.drawable.cpage_edit_effect_oldphoto,
					R.drawable.cpage_edit_effect_moonnight,
					R.drawable.cpage_edit_effect_oil,
					R.drawable.cpage_edit_effect_sketch
					};
		
		public void setSelectPosition(int position)
		{
			selectedIndex = position;
			notifyDataSetInvalidated();
		}
		@Override
		public int getCount() {
			return res.length;
		}

		@Override
		public Object getItem(int position) {
			return res[position];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			

			View view = convertView;
			if(view == null)
			{
				view =  LayoutInflater.from(EditImageActivity.this).inflate(R.layout.createpostcard_option_item, null);
				
			}
			
			ImageView icon =  (ImageView)view.findViewById(R.id.effect_icon);

			icon.setBackgroundResource(res[position]);
			ImageView selected =  (ImageView)view.findViewById(R.id.effect_selected);
			selected.setVisibility( selectedIndex == position ? View.VISIBLE : View.INVISIBLE);
			return view;
		
		}
		
	}


	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.edit_confirm)
		{
			Bitmap editImage = mEditImage.getScaledBitmapEx();
			if(editImage.getWidth()<EditPostcardView.EXPECTWIDTH || editImage.getHeight()<EditPostcardView.EXPECTHEIGHT)
			{
				
				String msg = "此图片因为尺寸过小，会影响印刷质量，是否继续？";
				
				//int w = mEditImage.getOrgWidth() > mEditImage.getOrgHeight()?  mEditImage.getOrgWidth(): mEditImage.getOrgHeight();
				//int h = mEditImage.getOrgWidth() < mEditImage.getOrgHeight()?  mEditImage.getOrgWidth(): mEditImage.getOrgHeight();
				int w =mEditImage.getOrgWidth();
				int h =mEditImage.getOrgHeight();
				//Toast.makeText(this, "原始图片宽度:"+w+", 高度:"+h, Toast.LENGTH_SHORT).show();
				if(mEditImage!= null && (w >=EditPostcardView.EXPECTWIDTH&&h >=EditPostcardView.EXPECTHEIGHT))
				{
					msg="请先缩放调整好照片的位置进行裁剪，印刷效果会更完美哦,是否继续?";
				}
				Utils.showConfirmDialog(this,msg, new Runnable()
				{

					@Override
					public void run() {
						Postcard currentPC = PostcardController.getInstance().getCurrentPostCard();
						//currentPC.image = mEditImage.getScaledBitmapEx();
						currentPC.setTmpEditPC(mEditImage.getScaledBitmapEx());
						OffLineManager.getInstance().getCurrentBackupPC().saveImage(mEditImage.getScaledBitmapEx());
						
						if(OffLineManager.getInstance().getCurrentBackupPC()!= null)
							OffLineManager.getInstance().updateOffLinePc(EditImageActivity.this, OffLineManager.getInstance().getCurrentBackupPC().getName(), 1);
						Intent nextPage = new Intent(EditImageActivity.this,EditTextActivity.class);
						EditImageActivity.this.startActivity(nextPage);
						
					}
					
				}, new Runnable()
				{

					@Override
					public void run() {
						// TODO Auto-generated method stub
						
					}
					
				});
				
				return;
			}
			Postcard currentPC = PostcardController.getInstance().getCurrentPostCard();
			//currentPC.image = editImage;
			currentPC.setTmpEditPC(editImage);
			OffLineManager.getInstance().getCurrentBackupPC().saveImage(editImage);
			
			if(OffLineManager.getInstance().getCurrentBackupPC()!= null)
				OffLineManager.getInstance().updateOffLinePc(this, OffLineManager.getInstance().getCurrentBackupPC().getName(), 1);
			Intent nextPage = new Intent(EditImageActivity.this,EditTextActivity.class);
			EditImageActivity.this.startActivity(nextPage);
		}
		else if(v.getId() == R.id.title_return)
		{
			finish();
		}
		else if(v.getId() == R.id.edit_rotat)
		{
			proccessImage(EFFECT_ROTAT,currentBitmap);
		
		}
		else if(v.getId() ==  R.id.edit_retake)
		{
			String[] arg0 = { getString(R.string.camera), getString(R.string.gallery) };
            Utils.showChooseDialog(this, arg0, new Runnable[] {
                new Runnable() {

                    @Override
                    public void run() {
                    	cameraUri =  ImageUtil.getImageFromCamera(EditImageActivity.this);
                    }
                    
                },
                new Runnable() {

                    @Override
                    public void run() {
                        ImageUtil.setImageFromGallery(EditImageActivity.this);
                    }
                    
                }
            });
			
		}
	}
	

	// 常用事件监听，用来处理通常的网络错误，授权验证错误等
	static class MyGeneralListener implements com.baidu.mapapi.MKGeneralListener {
		@Override
		public void onGetNetworkState(int iError) {
			Log.d("MyGeneralListener", "onGetNetworkState error is "+ iError);
		}

		@Override
		public void onGetPermissionState(int iError) {
			Log.d("MyGeneralListener", "onGetPermissionState error is "+ iError);
			if (iError ==  MKEvent.ERROR_PERMISSION_DENIED) {
			}
		}
	}
	public com.ilovepostcard.data.CurrentLocation currentLocation = new CurrentLocation();
	String mStrKey = "C5B5C926991D17D0F8DBFA47F6F4EB9933DBBB7F";
    private class GetAddressTask extends AsyncTask<Location,Void,String>{

		@Override
		protected String doInBackground(Location... params) {
			
			isLocationThreadRunning = true;
			Log.d(Constants.TAG,"execute");
			String resultStr = null;
			Location location=params[0];
			DefaultHttpClient client = new DefaultHttpClient();
	    	StringBuilder address_url_sb = new StringBuilder();
	    	address_url_sb.append(NET_BAIDU_LOC_URL);
	    	address_url_sb.append(location.getLatitude()+",");
	    	address_url_sb.append(location.getLongitude());
			address_url_sb.append("&key=eb471b1f42ca51ef63f6d8f11a358548");
			
			HttpGet httpGet = new HttpGet(address_url_sb.toString());
			
			HttpResponse resp;
			try {
				resp = client.execute(httpGet);
				HttpEntity entity = resp.getEntity();

				BufferedReader br = new BufferedReader(new InputStreamReader(
						entity.getContent()));

				StringBuffer sb = new StringBuffer();

				String r = br.readLine();

				while (r != null) {
					sb.append(r);
					r = br.readLine();
				}
				
				Log.d(Constants.TAG,"return="+sb.toString());
				JSONObject data = new JSONObject(sb.toString());
				String result = data.getString("status");
				if(result.equals("OK")){
					JSONObject addressObj = data.getJSONObject("result");
					//resultStr = addressObj.getString("formatted_address");
					Log.d(Constants.TAG,"resultStr" + addressObj.toString());
					
					
					JSONObject detail = addressObj.getJSONObject("addressComponent");
					String province  = detail.getString("province");
					String district = detail.getString("district");
					resultStr = province+"."+district;
					//district
				}
				
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			isLocationThreadRunning = false;
			return resultStr;
		}

		@Override
		protected void onPostExecute(String result) {
			Log.d(Constants.TAG,"result="+result);
			Postcard currentPC = PostcardController.getInstance().getCurrentPostCard();
			if(currentPC!= null)
				currentPC.location = result;

		}
		
    }
    
    private void enableLocationSettings() {
    	if(!isLocationInitialized){
    		if (mBMapMan == null) {
    			mBMapMan = new BMapManager(getApplication());
    			mBMapMan.init(mStrKey, new MyGeneralListener());
    		}
		
    		// 注册Listener
    		mBMapMan.getLocationManager().requestLocationUpdates(mLocationListener);
    		mBMapMan.start();
    		isLocationInitialized = true;
    	}
    }
    
    
    private LocationListener mLocationListener = new LocationListener(){

		@Override
		public void onLocationChanged(Location location) {
			
			if(location == null) return;
			
/*			if(oldLocation != null){
				if((Math.abs(oldLocation.getLatitude() - location.getLatitude()) < 0.0001) ||
						Math.abs(oldLocation.getLongitude() - location.getLongitude() ) < 0.001){
					return;
				}
			}else{
				oldLocation = location;
			}
			*/
			currentLocation.setmCurrLat(String.valueOf(location.getLatitude()));
			currentLocation.setmCurrLng(String.valueOf(location.getLongitude()));
			OffLinePostcard pc = OffLineManager.getInstance().getCurrentBackupPC();
			Postcard currentPC = PostcardController.getInstance().getCurrentPostCard();
			currentPC.latitude = location.getLatitude();
			currentPC.longitude = location.getLongitude();
			pc.save(OffLinePostcard.TAG_LATITUDE, currentPC.latitude+"");
			pc.save(OffLinePostcard.TAG_LONGITUDE, currentPC.longitude+"");
			if(!isLocationThreadRunning)
				new GetAddressTask().execute(location);

			
		}
    	
    };

}
